<?php


namespace app\common\server;

class Export
{
	public static function export($export_type, $file_name, $data, $field = 0)
	{
		$filedir = "../cache/file/" . date("Y") . "/" . date("m") . "/" . date("d") . "/";
		mkdirs($filedir);
		$key = uniqid();
		$filename = md5($key);
		if ($export_type == "excel") {
			$file_postfix = "xlsx";
			$filepath = $filedir . $filename . ".{$file_postfix}";
			$sheet_name = "sheet1";
			$objPHPExcel = new \PHPExcel();
			$objPHPExcel->getProperties()->setCreator("爱码科技")->setLastModifiedBy("Maarten Balliauw")->setTitle("Office 2007 XLSX Test Document")->setSubject("Office 2007 XLSX Test Document")->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")->setKeywords("office 2007 openxml php")->setCategory("Test result file");
			$objSheet = $objPHPExcel->getActiveSheet();
			$objSheet->setTitle($sheet_name);
			$objPHPExcel->getActiveSheet()->getStyle("1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB("FFFF00");
			$objPHPExcel->getActiveSheet()->getStyle("1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$objPHPExcel->getActiveSheet()->getStyle("1")->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$objPHPExcel->getActiveSheet()->getStyle("1")->getFont()->setBold(true);
			$objPHPExcel->getActiveSheet()->getStyle("1")->getFont()->getColor()->setRGB("FF0000");
			$objPHPExcel->getActiveSheet()->getRowDimension("1")->setRowHeight(20);
			$objSheet->fromArray($data);
			$objWrite = \PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
			$objWrite->save($filepath);
		} elseif ($export_type == "txt") {
			$file_postfix = "txt";
			$filepath = $filedir . $filename . ".{$file_postfix}";
			$content = "";
			array_shift($data);
			foreach ($data as $item) {
				if ($content) {
					$content .= "\n" . $item[$field];
				} else {
					$content = $item[$field];
				}
			}
			file_put_contents($filepath, $content);
		}
		$log = ["name" => $file_name . "." . $file_postfix, "path" => realpath($filepath), "create_time" => time(), "expire_time" => time() + 7200, "filesize" => filesize($filepath), "key" => $key];
		$logid = \think\Db::name("data_export_file")->insertGetId($log);
		$log["id"] = $logid;
		return $log;
	}
}